package cn.bossfriday.im.common.db;

import cn.bossfriday.common.exception.ServiceRuntimeException;
import cn.bossfriday.im.common.db.entity.UserInfo;
import cn.bossfriday.im.common.enums.user.UserStateType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Objects;

/**
 * UserInfoDao
 *
 * @author chenx
 */
@Slf4j
@Service
public class UserInfoDao {

    private static final String SQL_INSERT = "INSERT INTO user_info (appId, userId, userName, userPortrait, extension, updatedTime, regTime, state, userAgent) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
    private static final String SQL_GET_BY_ID = "SELECT * FROM user_info WHERE appId = ? AND userId = ?";

    /**
     * add
     *
     * @param userInfo
     * @return
     */
    public int add(UserInfo userInfo) throws SQLException {
        if (Objects.isNull(userInfo)) {
            throw new ServiceRuntimeException("The input userInfo is null!");
        }

        if (Objects.isNull(userInfo.getRegTime()) || Objects.isNull(userInfo.getUpdatedTime())) {
            Timestamp ts = DbUtilExecutor.now();
            userInfo.setRegTime(ts);
            userInfo.setUpdatedTime(ts);
        }

        return DbUtilExecutor.executeUpdate(
                SQL_INSERT,
                userInfo.getAppId(),
                userInfo.getUserId(),
                userInfo.getUserName(),
                userInfo.getUserPortrait(),
                userInfo.getExtension(),
                userInfo.getUpdatedTime(),
                userInfo.getRegTime(),
                UserStateType.NORMAL.getCode(),
                userInfo.getUserAgent()
        );
    }

    /**
     * getById
     *
     * @param appId
     * @param userId
     * @return
     */
    public UserInfo getById(long appId, String userId) {
        try {
            return DbUtilExecutor.queryObject(SQL_GET_BY_ID, UserInfo.class, appId, userId);
        } catch (Exception ex) {
            log.error("UserInfoDao.getById() error!", ex);
            throw new ServiceRuntimeException("UserInfoDao.getById() error!");
        }
    }
}
